import java.util.HashMap;
import java.util.Map;

/**
 * 面试题 16.02. 单词频率
 * https://leetcode-cn.com/problems/words-frequency-lcci/
 */
public class Solutions_mianshi_16_02 {
    public static void main(String[] args) {
        String[] books = {"i", "have", "an", "apple", "he", "have", "a", "pen"};
        WordsFrequency wordsFrequency = new WordsFrequency(books);
        int res1 = wordsFrequency.get("you");  // output: 0
        System.out.println(res1);
        int res2 = wordsFrequency.get("have");  // output: 2
        System.out.println(res2);
        int res3 = wordsFrequency.get("an");  // output: 1
        System.out.println(res3);
        int res4 = wordsFrequency.get("apple");  // output: 1
        System.out.println(res4);
        int res5 = wordsFrequency.get("pen");  // output: 1
        System.out.println(res5);
    }
}

class WordsFrequency {
    private Map<String, Integer> map = new HashMap<>();;

    public WordsFrequency(String[] book) {
        for (String b : book) {
            Integer count = get(b);
            map.put(b, count + 1);
        }
    }

    public int get(String word) {
//        Integer count = map.get(word);
//        return count == null ? 0 : count;
        return map.getOrDefault(word, 0);
    }
}
